package com.ambow.common.utils;

import com.ambow.apimodel.common.CeatShFileVo;
import com.jcraft.jsch.*;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.Properties;
/**
 * @author 周志伟
 * @projectname 项目名称: ${project_name}
 * @classname: UploadFileLinux
 * @description:
 * @date 2019/4/3：9:51
 */
@Log4j
public class UploadFileLinux {
    private static final int DEFAULT_PORT = 22;
    private static final int DEF_WAIT_SECONDS = 30;

    @Test
    public void Test() throws IOException, JSchException {
        this.createfile(CeatShFileVo.builder().shfilename("start").
                text("dasdjak").
                suffix("sh").
                dstfilepath("/opt/2323/").
                ip("172.24.132.107").
                username("root").
                password("123.abc").
                chmodcode("775").
                build());
    }


    public  void  createfile(CeatShFileVo ceatShFileVo) throws IOException, JSchException {
        String shname=ceatShFileVo.getDstfilepath()+ceatShFileVo.getShfilename()+"."+ceatShFileVo.getSuffix();
        Session session = openSession(ceatShFileVo.getIp(), ceatShFileVo.getUsername(), ceatShFileVo.getPassword(), DEF_WAIT_SECONDS);
        ChannelSftp openChannelSftp = openChannelSftp(session);
        String path= "E:\\GitWork\\riskManagement\\rm\\target\\rm-1.0.0.war";
        try {
            if (!isDirExist(ceatShFileVo.getDstfilepath(),openChannelSftp)){
                openChannelSftp.mkdir(ceatShFileVo.getDstfilepath());
            }
            openChannelSftp.put(path, ceatShFileVo.getDstfilepath(), ChannelSftp.OVERWRITE);
            openChannelSftp.chmod(Integer.parseInt(ceatShFileVo.getChmodcode(),8),shname);
            openChannelSftp.exit();

        } catch (Exception e) {
            log.info("上传脚本异常");
            e.printStackTrace();
        }

    }




    /**
     * 创建服务器连接
     *
     * @param host
     *            主机
     * @param user
     *            用户
     * @param password
     *            密码
     * @param waitSeconds
     *            等待秒数
     * @return
     */
    private  Session openSession(String host, String user, String password, int waitSeconds) throws JSchException {
        Session session = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(user, host, DEFAULT_PORT);
            noCheckHostKey(session);
            session.setPassword(password);
            // 这个设置很重要，必须要设置等待时长为大于等于2分钟
            session.connect(waitSeconds * 2000);
            if (!session.isConnected()) {
                throw new IOException("We can't connection to[" + host + "]");
            }
        }catch (JSchException jSchException){
            throw new  JSchException("用户名或者密码不对，没有权限访问ip为："+host);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return session;
    }

    /**
     * 不作检查主机键值
     *
     * @param session
     */
    private  void noCheckHostKey(Session session) {
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
    }

    /**
     * 连接shell
     *
     * @param session
     *            session
     * @return {@link ChannelShell}
     */
    private  ChannelShell openChannelShell(Session session) {
        ChannelShell channel = null;
        try {
            channel = (ChannelShell) session.openChannel("shell");
            channel.setEnv("LANG", "en_US.UTF-8");
            channel.setAgentForwarding(false);
            channel.setPtySize(500, 500, 1000, 1000);
            channel.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (channel == null) {
            throw new IllegalArgumentException("The channle init was wrong");
        }
        return channel;
    }

    /**
     * 连接sftp
     *
     * @param session
     * @return {@link ChannelSftp}
     */
    private  ChannelSftp openChannelSftp(Session session) {
        ChannelSftp channel = null;
        try {
            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return channel;
    }

    /**
     * 判断目录是否存在
     */
    public  boolean isDirExist(String directory,ChannelSftp sftp) {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpATTRS = sftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }

@Test
  public void test() throws JSchException, IOException {
      CeatShFileVo ceatShFileVo = CeatShFileVo.builder().shfilename("start").
              text("dasdjak").
              suffix("sh").
              dstfilepath("/opt/2323/").
              ip("172.24.132.107").
              username("root").
              password("123.abc").
              chmodcode("775").
              build();
      Session session = openSession(ceatShFileVo.getIp(), ceatShFileVo.getUsername(), ceatShFileVo.getPassword(), DEF_WAIT_SECONDS);


      ChannelShell channel =this.openChannelShell(session);

      InputStream inputStream = channel.getInputStream();//从远程端到达的所有数据都能从这个流中读取到
      OutputStream outputStream = channel.getOutputStream();//写入该流的所有数据都将发送到远程端。
      PrintWriter printWriter = new PrintWriter(outputStream);
      String cmd = "cd /sh && ./laqu.sh http://'zhouzhiwei':'zhouzhiwei1'@code.edurp.com/edurp-personal-credit/job-center.git  1d2b2036a8f499bef42c5cb5fb04e26f45cdfaee";
      printWriter.println(cmd);
      printWriter.println("exit");//加上个就是为了，结束本次交互
      printWriter.flush();
   //     String result = IOUtils.toString(inputStream);

   // System.out.println(result);
    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
      String msg = null;
      int i =0;
      while((msg = in.readLine())!=null){
          i++;
          if (StringUtils.isNoneBlank(msg)){
              if (i>4)
              System.out.println(msg);

          }
      }
      in.close();
        inputStream.close();
        outputStream.close();
        printWriter.close();

  }

    @Test
    public void test2() throws JSchException, IOException {
        CeatShFileVo ceatShFileVo = CeatShFileVo.builder().shfilename("start").
                text("dasdjak").
                suffix("sh").
                dstfilepath("/opt/2323/").
                ip("172.24.161.68").
                username("root").
                password("123.abc").
                chmodcode("775").
                build();
        Session session = openSession(ceatShFileVo.getIp(), ceatShFileVo.getUsername(), ceatShFileVo.getPassword(), DEF_WAIT_SECONDS);
        String command = " cd /data/service/yun/  && ./ganya.sh restart   edurp-gateway-0.0.1.jar  gateway";


        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand(command);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        String result = IOUtils.toString(in);
        System.out.println(result);
        channelExec.disconnect();
    }


}
